package com.hym.hymlistview;

import java.text.SimpleDateFormat;
import java.util.Date;

import com.hym.myrrefreshlistview.R;

import android.content.Context;
import android.util.AttributeSet;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.RotateAnimation;
import android.widget.AbsListView;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.ListView;
/**
 * 
 * @description：
 * 慕课网版本
 * @author： HuYuMian
 *
 * @QQ：732476506
 *   
 * @version：
 *
 * @time：2015-9-1
 *
 */
public class HymListview_mk extends ListView implements OnScrollListener {

	/** listView的头部 */
	private View header;
	/** header布局的高度 */
	private int headerHeight;
	/** 当前可见的第一个item的位置 */
	int firstVisibleItem;
	/** listView的滚动状态 */
	int scrollState;
	/** 标记当前是在listView最顶端按下 */
	boolean isRemark;
	/** 记录按下时的起始Y值 */
	int startY;
	/** headerView的状态 */
	int state;
	/** 正常状态：headerView隐藏 */
	final int NONE = 0;
	/** 提示下拉状态 */
	final int PULL = 1;
	/** 提示释放状态 */
	final int RELEASE = 2;
	/** 正在刷新状态 */
	final int REFRESHING = 3;
	
	/** 刷新数据的接口*/
	IRefreshListener mIRefreshListener;
	
	/** 设置接口*/
	public void setIRefreshListener(IRefreshListener iRefreshListener){
		mIRefreshListener=iRefreshListener;
	}

	public HymListview_mk(Context context) {
		super(context);
		initView(context);
	}

	public HymListview_mk(Context context, AttributeSet attrs) {
		super(context, attrs);
		initView(context);
	}
	public HymListview_mk(Context context, AttributeSet attrs, int defStyle) {
		super(context, attrs, defStyle);
		initView(context);
	}

	/**
	 * 初始化界面，添加顶部布局文件到ListView
	 * 
	 * @param context
	 */
	private void initView(Context context) {
		LayoutInflater inflater = LayoutInflater.from(context);
		header = inflater.inflate(R.layout.header_layout, null);
		// 这种方式获取高度获取不到：因为只有一个控件的onMeasure方法执行完成以后
		// 才能通过这种方式获得控件的测量高度,所以在activity的oncreate方法，也是
		// 获取不到高度的。
		// ①对于控件本身而言，必须是通知了父布局自己的宽高过后，才能通过getMeasur
		// eHeight方法得到实际的高度；
		// ②对于activity中，可以通过观查者的方法获取高度。
		measureView(header);
		headerHeight = header.getMeasuredHeight();
		// Log.e("test——headerHeight:", headerHeight+"");
		topPadding(-headerHeight);
		this.addHeaderView(header);
		this.setOnScrollListener(this);
	}

	/**
	 * 通知父布局view占用的宽高
	 * 
	 * @param view
	 */
	private void measureView(View view) {
		ViewGroup.LayoutParams p = view.getLayoutParams();
		// p==null,未设置布局参数或者设置布局参数的方法调用失败
		if (p == null) {
			p = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
					ViewGroup.LayoutParams.WRAP_CONTENT);
		}
		int width = ViewGroup.getChildMeasureSpec(0, 0, p.width);
		int height;
		int tempHeight = p.height;
		if (tempHeight > 0) {
			// makeMeasureSpec:基于尺寸和测量模型创建一个测量规格
			height = MeasureSpec.makeMeasureSpec(tempHeight,
					MeasureSpec.EXACTLY);
		} else {
			height = MeasureSpec.makeMeasureSpec(tempHeight,
					MeasureSpec.UNSPECIFIED);
		}
		view.measure(width, height);
	}

	/**
	 * 设置padding布局的上边距 取header控件高度的负值
	 * 
	 * @param topPadding
	 */
	private void topPadding(int topPadding) {
		header.setPadding(header.getPaddingLeft(), topPadding,
				header.getPaddingRight(), header.getPaddingBottom());
		header.invalidate();
	}

	@Override
	public void onScroll(AbsListView view, int firstVisibleItem,
			int visibleItemCount, int totalItemCount) {
		this.firstVisibleItem = firstVisibleItem;
	}

	@Override
	public void onScrollStateChanged(AbsListView view, int scrollState) {
		this.scrollState = scrollState;
		Log.e("scrollState:", scrollState + "");
	}

	@Override
	public boolean onTouchEvent(MotionEvent ev) {
		switch (ev.getAction()) {
		case MotionEvent.ACTION_DOWN:
			if (firstVisibleItem == 0) {
				isRemark = true;
				startY = (int) ev.getY();
			}
			break;
		case MotionEvent.ACTION_MOVE:
			onMove(ev);
			break;
		case MotionEvent.ACTION_UP:
			if (state == RELEASE) {
				state = REFRESHING;
				refreshViewByState(state);
				// 加载新数据
				mIRefreshListener.onRefresh();
			} else if (state == PULL) {
				// 恢复状态
				state = NONE;
				refreshViewByState(state);
				isRemark = false;
			}
			break;
		}
		return super.onTouchEvent(ev);
	}

	/**
	 * 移动过程所执行的操作
	 * 
	 * @param ev
	 */
	public void onMove(MotionEvent ev) {
		// 非可操作状态，不执行任何操作
		if (!isRemark) {
			return;
		}
		int tempY = (int) ev.getY();
		int distance = tempY - startY;
		// 让headerView随着移动显示，通过设置paddingTop值实现
		int topPadding = distance - headerHeight;
		Log.e("distance|headerheight", distance+"|"+headerHeight);
		Log.e("paddding:", topPadding+"");
		switch (state) {
		case NONE:
			if (distance > 0) {
				state = PULL;
				refreshViewByState(state);
			}
			break;
		case PULL:
			topPadding(topPadding);
			if (distance > headerHeight + 30
					&& scrollState == SCROLL_STATE_TOUCH_SCROLL) {
				state=RELEASE;
				refreshViewByState(state);
			}
			break;

		case RELEASE:
			topPadding(topPadding);
			if(distance<headerHeight+30){
				state=PULL;
				refreshViewByState(state);
			}else if(distance<=0){
				//恢复所有状态
				state=NONE;
				refreshViewByState(state);
				isRemark=false;
			}
			break;
		}
		
		
	}
	
	/**
	 * 根据当前状态，改变header中的界面的显示
	 * @param state
	 */
	private void refreshViewByState(int state){

		TextView tip = (TextView) header.findViewById(R.id.tip);
		ImageView arrow = (ImageView) header.findViewById(R.id.arrow);
		ProgressBar progress = (ProgressBar) header.findViewById(R.id.progress);
		RotateAnimation anim = new RotateAnimation(0, 180,
				RotateAnimation.RELATIVE_TO_SELF, 0.5f,
				RotateAnimation.RELATIVE_TO_SELF, 0.5f);
		anim.setDuration(500);
		anim.setFillAfter(true);
		RotateAnimation anim1 = new RotateAnimation(180, 0,
				RotateAnimation.RELATIVE_TO_SELF, 0.5f,
				RotateAnimation.RELATIVE_TO_SELF, 0.5f);
		anim1.setDuration(500);
		anim1.setFillAfter(true);
		switch (state) {
		case NONE:
			arrow.clearAnimation();
			topPadding(-headerHeight);
			break;

		case PULL:
			arrow.setVisibility(View.VISIBLE);
			progress.setVisibility(View.GONE);
			tip.setText("下拉可以刷新！");
			arrow.clearAnimation();
			arrow.setAnimation(anim1);
			break;
		case RELEASE:
			arrow.setVisibility(View.VISIBLE);
			progress.setVisibility(View.GONE);
			tip.setText("松开可以刷新！");
			arrow.clearAnimation();
			arrow.setAnimation(anim);
			break;
		case REFRESHING:
			topPadding(50);
			arrow.setVisibility(View.GONE);
			progress.setVisibility(View.VISIBLE);
			tip.setText("正在刷新...");
			arrow.clearAnimation();
			break;
		}
	
	}
	
	/**
	 * 获取完数据，或者刷新操作完成
	 */
	public void refreshCompleted(){
		state=NONE;
		isRemark=false;
		refreshViewByState(state);
		//设置一下上次更新的时间
		TextView lastupdatetime = (TextView) header
				.findViewById(R.id.lastupdate_time);
		SimpleDateFormat format = new SimpleDateFormat("yyyy年MM月dd日 hh:mm:ss");
		Date date = new Date(System.currentTimeMillis());
		String time = format.format(date);
		lastupdatetime.setText(time);
	}
	
	/**
	 * 刷新数据的接口
	 */
	public interface IRefreshListener{
		void onRefresh();
	}

}
